package org.xiaojl.utils;

import javax.servlet.http.HttpServletRequest;

import org.xiaojl.common.SessionUser;
import org.xiaojl.constants.Constants;

public class WebUtil {

	/**
	 * 添加当前登录用户到session中
	 * 
	 * @param request
	 * @param sessionUser
	 * @return
	 */
	public static SessionUser setSessionUser(HttpServletRequest request,SessionUser sessionUser){
		request.getSession().setAttribute(Constants.SESSION_USER, sessionUser);
		return sessionUser;
	}
	
	/**
	 * 获取当前登录用户
	 * 
	 * @param request
	 * @return
	 */
	public static SessionUser getSessionUser(HttpServletRequest request){
		return (SessionUser) request.getSession().getAttribute(Constants.SESSION_USER);
	}
	
	/**
	 * 获取访问IP地址
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddress(HttpServletRequest request){
		String ip = request.getHeader("Cdn-Src-Ip");
		String localIP = "127.0.0.1";
		if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase(localIP) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("x-forwarded-for");
		}
		if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase(localIP) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase(localIP) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || (ip.equalsIgnoreCase(localIP))) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || (ip.equalsIgnoreCase(localIP))) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || (ip.equalsIgnoreCase(localIP))) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
